import { reactive, getCurrentInstance, toRaw, ref } from 'vue';
// import { MQJ_TOKEN, EXP_PHONE, USERID, USERINFO } from '@/mqj/mqj.config';
import { Form } from 'ant-design-vue';
import { message } from 'ant-design-vue';
import Api from './api';
const useForm = Form.useForm;

export function useLogin(context) {
  const loginState = reactive({
    form: {
      account: '',
      password: '',
    },
    loading: false,
  });

  const rules = reactive({
    account: [{ required: true, message: '账户必填', trigger: 'blur' }],
    password: [{ required: true, message: '密码必填', trigger: 'blur' }],
  });
  const g = getCurrentInstance().appContext.config.globalProperties;
  const mu = g.$router;
  const { validate, validateInfos } = useForm(loginState.form, rules);
  const submit = (f) => {
    loginState.loading = true;
    Api.login(toRaw(loginState.form)).then(
      (res) => {
        localStorage.setItem(MQJ_TOKEN, res.data.token);
        localStorage.setItem(USERID, res.data.account_id);
        localStorage.setItem(USERINFO, JSON.stringify(res.data));
        loginState.loading = false;
        g.$userInfo = res.data;
        mu.push({
          path: '/space/cms/banner/list',
        });
      },
      (res) => {
        loginState.loading = false;
      }
    );
  };

  return {
    loginState,
    rules,
    validateInfos,
    submit,
  };
}

export function useCode(loginState) {
  const seconds = 60;
  const codeState = reactive({
    codeText: '发送验证码',
    codeSeconds: seconds,
    disabled: false,
  });

  const interval = () => {
    codeState.codeSeconds = seconds - 1;
    codeState.disabled = true;
    codeState.codeText = `重新发送(${codeState.codeSeconds})`;
    let t = setInterval(() => {
      codeState.codeSeconds--;
      codeState.codeText = `重新发送(${codeState.codeSeconds})`;
      if (codeState.codeSeconds <= 0) {
        codeState.disabled = false;
        codeState.codeText = '重新发送';
        clearInterval(t);
      }
    }, 1000);
  };

  const sendcode = () => {
    if (!EXP_PHONE.test(loginState.form.phone)) {
      message.warning('手机号码格式不正确');
      return;
    }
    Api.sendCode({
      phone: loginState.form.phone,
      scene: 'm_login',
    }).then((res) => {});
    interval();
  };

  return {
    codeState,
    sendcode,
  };
}
